<script setup lang="ts">
defineOptions({
  name: "ALL_FAB_MAINTENANCE_PMPLAN"
});

import { ref, customRef, provide, onMounted, onUnmounted } from "vue";
import planHeader from "./components/planHeader.vue";
import factory from "./components/factory.vue";
import workbench from "./components/workbench.vue";
import { queryFabFactoryRelationIds } from "@/api/modules/fab";
import {
  SizeType,
  WidthKey,
  HeightKey,
  ChartListType,
  ChartTypeType,
  ChartListKey,
  ChartTypeKey,
  SelectionChangeCallBackType,
  SelectionChangeCallBackTypeKey,
  LockChangeCallBackType,
  LockChangeCallBackTypeKey,
  SelectionDataType,
  SelectionDataKey,
  ExportCallBackType,
  ExportCallBackTypeKey,
  LockType,
  FactoryLockTypeKey,
  WorkbenchLockTypeKey
} from "./utils";
import { emitter } from "@/utils/mitt";

const pmPlanHeaderRef = ref(null);
const factoryRef = ref<InstanceType<typeof factory> | null>(null);
const workbenchRef = ref<InstanceType<typeof workbench> | null>(null);
const width = ref<number>(0);
const height = ref<number>(0);
const selectionData = ref<Record<string, Array<any>>>({
  factorySelectionData: [],
  workbenchSelectionData: []
});

provide<SelectionDataType>(SelectionDataKey, selectionData);
provide<SizeType>(WidthKey, width);
provide<SizeType>(HeightKey, height);
// 1  厂务PM计划     2   机台PM计划
const chartList = ref<Array<number>>([1]);
// gunter  甘特图   chart  table图
const chartType = ref<string>("gunter");

provide<ChartListType>(ChartListKey, chartList);
provide<ChartTypeType>(ChartTypeKey, chartType);

const factoryLock = customRef((track, trigger) => {
  let f: boolean = false;
  return {
    get() {
      track();
      return f;
    },
    set(newValue: boolean) {
      if (newValue) {
        if (workbenchLock.value) {
          workbenchLock.value = false;
        }
      }
      f = newValue;
      trigger();
    }
  };
});

const workbenchLock = customRef((track, trigger) => {
  let f: boolean = false;
  return {
    get() {
      track();
      return f;
    },
    set(newValue: boolean) {
      if (newValue) {
        if (factoryLock.value) {
          factoryLock.value = false;
        }
      }
      f = newValue;
      trigger();
    }
  };
});

provide<LockType>(FactoryLockTypeKey, factoryLock);
provide<LockType>(WorkbenchLockTypeKey, workbenchLock);

const updateSize = () => {
  if (!pmPlanHeaderRef.value) return;
  width.value = pmPlanHeaderRef.value.clientWidth;
  const { innerHeight } = window;
  const clinetTop = pmPlanHeaderRef.value.getBoundingClientRect().top;
  const totalHeight = innerHeight - clinetTop - 40 - 32;
  if (chartList.value.length < 2) {
    height.value = totalHeight - 34 - 16;
  } else {
    height.value = Math.floor((totalHeight - 16) / 2) - 34 - 16;
  }
};

const selectionChangeCallBack = async (type: "factory" | "workbench", data: Array<any> | null) => {
  if (!data?.length) {
    if (type === "factory") {
      selectionData.value.factorySelectionData.splice(0);
      factoryRef.value && factoryRef.value.clearSelection();
      if (chartList.value.length === 2 && factoryLock.value) {
        workbenchRef.value?.submitHandler({ deviceIdList: [] });
      }
    } else if (type === "workbench") {
      selectionData.value.workbenchSelectionData.splice(0);
      workbenchRef.value && workbenchRef.value.clearSelection();
      if (chartList.value.length === 2 && workbenchLock.value) {
        factoryRef.value?.submitHandler({ deviceIdList: [] });
      }
    }
    return;
  }
  let ids: Array<any> = [];
  ids = data.map(item => item.deviceId);
  ids = Array.from(new Set(ids));
  await queryRelationListFn(type, ids);
};

const queryRelationListFn = async (type: "factory" | "workbench", ids: Array<any> | null) => {
  let queryFab = false;
  if (type === "factory") {
    // 通过设备查询机台，是true，如果是通过机台查设备则给false
    queryFab = true;
  } else if (type === "workbench") {
    queryFab = false;
  }
  let res: Array<any> = [];
  if (!ids.length) {
    res = [];
  } else if (factoryLock.value || workbenchLock.value) {
    res = await queryFabFactoryRelationIds({ ids, queryFab });
  }
  if (type === "factory") {
    selectionData.value.factorySelectionData.splice(0);
    selectionData.value.factorySelectionData.push(...ids);
    if (factoryLock.value) {
      if (res?.length) {
        workbenchRef.value?.submitHandler({ deviceIdList: res });
      } else {
        workbenchRef.value.tableData = [];
      }
    }
  } else if (type === "workbench") {
    selectionData.value.workbenchSelectionData.splice(0);
    selectionData.value.workbenchSelectionData.push(...ids);
    if (workbenchLock.value) {
      if (res?.length) {
        // factoryRef.value?.submitHandler({ eqpIdList: res });
        factoryRef.value?.submitHandler({ deviceIdList: res });
      } else {
        factoryRef.value.tableData = [];
      }
    }
  }
};

provide<SelectionChangeCallBackType>(SelectionChangeCallBackTypeKey, selectionChangeCallBack);

const lockChangeCallBack = async (type: "factory" | "workbench", isLock: boolean) => {
  if (chartList.value.length === 2) {
    workbenchRef.value.clearSelection();
    selectionData.value.workbenchSelectionData.splice(0);
    factoryRef.value.clearSelection();
    selectionData.value.factorySelectionData.splice(0);
  }
};

provide<LockChangeCallBackType>(LockChangeCallBackTypeKey, lockChangeCallBack);

const exportCallBack = async (type: "factory" | "workbench") => {
  if (type === "factory") {
    console.info("厂务pm计划导出功能正在开发中，敬请期待。。。");
    factoryRef.value.exportFn();
  } else if (type === "workbench") {
    workbenchRef.value.exportFn();
  }
};

provide<ExportCallBackType>(ExportCallBackTypeKey, exportCallBack);

const changeHandler = () => {
  if (chartList.value.length < 2) {
    factoryLock.value = false;
    workbenchLock.value = false;
  }
  updateSize();
};

const init = () => {
  updateSize();
  window.addEventListener("resize", updateSize, true);
  emitter.on("tagViewsChange", async () => {
    await updateSize();
  });
};

onMounted(() => {
  init();
});

onUnmounted(() => {
  window.removeEventListener("resize", updateSize);
  emitter.off("tagViewsChange");
});
</script>

<template>
  <div class="fab-pm-plan">
    <div ref="pmPlanHeaderRef" class="pm-plan-header">
      <planHeader v-model:chartList="chartList" v-model:chartType="chartType" @change="changeHandler" />
    </div>
    <div v-if="chartList.includes(1)" :key="chartType" class="pm-plan-factory">
      <factory ref="factoryRef" v-model:lock="factoryLock" :selectionData="selectionData.factorySelectionData" />
    </div>
    <div v-if="chartList.includes(2)" :key="chartType" class="pm-plan-workbench">
      <workbench ref="workbenchRef" v-model:lock="workbenchLock" :selectionData="selectionData.workbenchSelectionData" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.fab-pm-plan {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
  height: 100%;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;

  .pm-plan-header {
    width: 100%;
  }

  .pm-plan-factory {
    flex: 1;
    width: 100%;
  }

  .pm-plan-workbench {
    flex: 1;
    width: 100%;
  }
}
</style>
